﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;
using Git.Storage.Common.ValidateRules;
using Git.Storage.Common.Result;
using Git.Storage.DTO.EntityDTO;

namespace Git.Storage.WebApi.Utility.Filters
{
    /// <summary>
    ///  DTO实体统一验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class ValidateAsyncActionFilterAttribute : Attribute, IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            List<object?> requstList = context.ActionArguments.Where(it => it.Value is BaseDTO && it.Value is not null)
                 .Select(it => it.Value)
                 .ToList();
            List<(bool, string?)> resList = new List<(bool, string?)>();

            foreach (object? item in requstList)
            {
                foreach (var itemProp in item!.GetType().GetProperties())
                {
                    if (itemProp.IsDefined(typeof(BaseValidateAttribute), true))
                    {
                        BaseValidateAttribute? baseValidate = itemProp.GetCustomAttribute<BaseValidateAttribute>();
                        resList.Add(baseValidate!.DoAction(itemProp.GetValue(item)!));

                    }
                }
            }
            if (resList.Any(it => it.Item1 == false))
            {
                context.Result = new JsonResult(new ApiResult()
                {
                    Message = string.Join(',', resList.Select(it => it.Item2)),
                    Success = false
                });
            }
            else
            {
                await next();
            }

        }
    }
}
